<template>
  <div>
    <el-dialog
      title="告警!"
      :visible.sync="isWarn"
      width="50%">
      <h3 style="color: red">您有一条告警信息!</h3>
      <h4 style="color: black"><el-form>

        <el-form-item label="抓拍图片">
          <img :src="deployAlarm.image" />
        </el-form-item>
      </el-form></h4>
      <h4 style="color: red">请立刻去查看!</h4>
      <audio ref="audio" class="aud">
<!--      <source :src="mp3url" />-->
      </audio>
      <el-button type="primary" @click="handleClose">确认</el-button>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "WebSocket",
  data() {
    return {
      deployAlarm: {},
      deployTaskFace: {},
      // mp3url: "",
      isConditionMet: false, // 初始状态，条件未满足
      message: '',
      isWarn: false,
      // ws是否启动
      wsIsRun: false,
      // 定义ws对象
      webSocket: null,
      // ws请求链接（类似于ws后台地址）
      ws: '',
      // ws定时器
      wsTimer: null,
      // music: new Audio()
    }
  },
  created() {
    this.music = require('@/api/Music/fenggexing_xiaoafeng.mp3');
  },
  async mounted() {
    this.wsIsRun = true
    this.wsInit()
  },
  methods: {
    parseAndAssignValues(message) {
      try {
        const data = JSON.parse(message);
        this.deployAlarm = data.deployAlarm;
        this.deployTaskFace = data.deployTaskFace;
      } catch (error) {
        console.error('Error parsing JSON:', error);
      }
    },

    openaudio() {
      // 确保音频元素和音频源都已定义
      if (this.$refs.audio && this.mp3url) {
        // 设置音频源
        this.$refs.audio.src = this.mp3url;
        // 尝试播放音频
        this.$refs.audio.play()
          .catch(e => {
            // 打印错误信息，但继续执行
            console.error('Audio playback failed: ', e);
          });
      } else {
        console.error('Audio element or mp3url is not defined.');
      }
    },
    wsMessageHanler(e) {
      this.message = e.data;
      this.parseAndAssignValues(this.message)
      // 确保 this.music 是一个有效的 URL 字符串
      this.mp3url = this.music; // 这里假设 this.music 是通过 require 正确导入的 URL 字符串
      this.isWarn = true;
      this.$nextTick(() => {
        this.openaudio();
      });
    },
    handleClose() {
      this.isWarn = false;
      // 这里可以添加关闭对话框后需要执行的逻辑
    },
    sendDataToServer() {
      if (this.webSocket.readyState === 1) {
        this.webSocket.send('来自前端的数据')
      } else {
        throw Error('服务未连接')
      }
    },

    /**
     * 初始化ws
     */
    wsInit() {
      const wsuri = 'http://127.0.0.1:19111/websocket/badao'
      this.ws = wsuri
      if (!this.wsIsRun) return
      // 销毁ws
      this.wsDestroy()
      // 初始化ws
      this.webSocket = new WebSocket(this.ws)
      // ws连接建立时触发
      this.webSocket.addEventListener('open', this.wsOpenHanler)
      // ws服务端给客户端推送消息
      this.webSocket.addEventListener('message', this.wsMessageHanler)
      // ws通信发生错误时触发
      this.webSocket.addEventListener('error', this.wsErrorHanler)
      // ws关闭时触发
      this.webSocket.addEventListener('close', this.wsCloseHanler)

      // 检查ws连接状态,readyState值为0表示尚未连接，1表示建立连接，2正在关闭连接，3已经关闭或无法打开
      clearInterval(this.wsTimer)
      this.wsTimer = setInterval(() => {
        if (this.webSocket.readyState === 1) {
          clearInterval(this.wsTimer)
        } else {
          console.log('ws建立连接失败')
          this.wsInit()
        }
      }, 3000)
    },
    wsOpenHanler(event) {
      console.log('ws建立连接成功')
    },
    /**
     * ws通信发生错误
     */
    wsErrorHanler(event) {
      console.log(event, '通信发生错误')
      this.wsInit()
    },
    /**
     * ws关闭
     */
    wsCloseHanler(event) {
      console.log(event, 'ws关闭')
      this.wsInit()
    },
    /**
     * 销毁ws
     */
    wsDestroy() {
      if (this.webSocket !== null) {
        this.webSocket.removeEventListener('open', this.wsOpenHanler)
        this.webSocket.removeEventListener('message', this.wsMessageHanler)
        this.webSocket.removeEventListener('error', this.wsErrorHanler)
        this.webSocket.removeEventListener('close', this.wsCloseHanler)
        this.webSocket.close()
        this.webSocket = null
        clearInterval(this.wsTimer)
      }
    }
  },
}
</script>

<style scoped>

</style>
